import { Form, Row, Col, Input, Button, Table, Spin, Space, Badge } from 'antd';
import { Ref, useEffect, useMemo, useRef, useState } from 'react';

import { getSelectExpertsColumns } from '../mconfig';
import '../common/styles.less';

import { Descriptions, useDescriptions } from '@/components/Descriptions';
import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { getLoadMapList, getSelectDataCommon, getTenantID, onCloseModalCommon } from '@/utils';
import { SearchOutlined, RedoOutlined, FilterOutlined } from '@ant-design/icons';
import { ExpertManageService } from '../services';
import { getExtractExpertsDataGrid } from '../services';
import { ILoadMapTypeAll } from '@/common';
import { ExtractListDrawer } from './ExtractListDrawer';
import { commonPageSizeOptions } from '@/common/constVariable';
/**
 * @ExpertsListModal 评标专家弹窗
 * @param onSave 保存事件
 * @param onClose 关闭事件
 * @returns
 */
const ExpertsListModal = ({ onSave, onClose, dataSource }: Record<string, any>) => {
  /** 弹窗Ref */
  const oneModalRef: Ref<IOneModalRef> = useRef(null);

  /** 表单Form */
  const [searchForm] = Form.useForm();

  /** 子组件表单ref  第二步步骤 */
  const extractFormRef = useRef<Record<string, any>>(null);

  /** 样式 */
  const className = 'expertsList-modalSelect';

  /** 列表与表单渲染状态 */
  const [isShowFrom, setIsShowFrom] = useState<boolean>(true);

  /** Table */
  const [rowList, setRowList] = useState<Record<string, any>[]>([]);

  /** 是否显示 【抽取专家弹窗】 */
  const [isShowExtractModal, setIsShowExtractModal] = useState(false);

  /** 专家库services */
  const { expertRun, expertDataSource, expertLoading, expertTableProps } = ExpertManageService();

  const extractExpertsCallBack = () => {};

  /**抽取专家接口 */
  const { extractExpertsRun, extractExpertsLoading, extractExpertsData } = getExtractExpertsDataGrid(extractExpertsCallBack);

  /** 证件类型数据字典 */
  const loadMdicIds: string[] = [`${getTenantID()}${ILoadMapTypeAll.EXPERTS_CARD_TYPE}`];
  const { loadMapInfo, mapLoading } = getLoadMapList(loadMdicIds);
  const experts_type = getSelectDataCommon(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.EXPERTS_CARD_TYPE}`], 'name', 'id');

  const [config, methods] = useDescriptions({
    name: 'add-experts',
    labelWidth: 220,
    schemas: [
      {
        label: '姓名',
        field: 'fullName',
        component: 'Input',
        required: true,
      },
      {
        label: '联系方式',
        field: 'phoneMobile',
        component: 'Input',
        required: true,
      },
      {
        label: '证件类型',
        field: 'cardType',
        component: 'Select',
        options: experts_type,
        fieldNames: { label: 'name', value: 'value' },
        required: true,
      },
      {
        label: '证件号码',
        field: 'cardNum',
        component: 'Input',
        required: true,
      },
      {
        label: '职务',
        field: 'positionName',
        component: 'Input',
        required: true,
      },
      {
        label: '职称',
        field: 'titleTech',
        component: 'Input',
        required: true,
      },
      {
        label: '工作单位',
        field: 'companyName',
        component: 'Input',
        colSpan: 2,
        required: true,
      },
    ],
  });

  // // /** 保存事件 */
  // const onModalOk = async () => {
  //   let returnArr: any = null;
  //   if (!isShowFrom) {
  //     const result = await methods?.validateFields();
  //     returnArr = [{ ...result, expertFlag: 1 }];
  //   } else {
  //     returnArr = rowList;
  //   }
  //   rowList?.forEach((item) => (item.sourceType = 0));
  //   console.log(rowList, '===============>>>>>')
  //   onSave(rowList, isShowFrom);
  //   onCloseModalCommon(oneModalRef);
  // };

  // /** 保存事件 */
  const onModalOk = async () => {
    let returnArr: any = null;
    if (!isShowFrom) {
      const result = await methods?.validateFields();
      returnArr = [{ ...result, expertFlag: 1, sourceType: 0 }];
      onSave(returnArr, isShowFrom);
    } else {
      returnArr = rowList?.forEach((item) => (item.sourceType = 0));
      onSave(rowList, isShowFrom);
    }
    onCloseModalCommon(oneModalRef);
  };

  /** Table选择方法 */
  const onSelectChange = (_: React.Key[], selectedRows: Record<string, any>[]) => {
    setRowList(selectedRows);
  };

  /** 底部按钮 */
  const footerRender = () => {
    return (
      <>
        {
          <Button
            // icon={<PlusCircleOutlined />}
            type={'primary'}
            onClick={() => setIsShowFrom(!isShowFrom)}
          >
            {isShowFrom ? '添加' : '选择'}
          </Button>
        }
        <Button
          onClick={() => onCloseModalCommon(oneModalRef)}
          // icon={<CloseCircleOutlined />}
        >
          取消
        </Button>
        <Button
          type={'primary'}
          onClick={onModalOk}
          // icon={<CheckCircleOutlined />}
        >
          确认
        </Button>
      </>
    );
  };

  /** 初始请求 */
  useEffect(() => {
    expertRun({ current: 1, pageSize: 10 });
  }, []);

  /** 抽取专家 */
  const onExtract = () => {
    setIsShowExtractModal(true);
  };

  /** 重置 */
  const onReset = () => {
    searchForm?.resetFields();
    expertRun({ current: 1, pageSize: 10 });
  };

  /** 搜索 */
  const onSearch = async () => {
    const formResult = await searchForm?.getFieldsValue();
    expertRun({ current: 1, pageSize: 10, ...formResult });
  };

  /** 有抽选数据时  调用【抽选专家】 接口*/
  const onSearchExtract = async () => {
    const reqList = extractFormRef?.current?.firstForm?.getFieldValue('extractTable');
    const mapList = reqList?.map((item) => {
      return {
        ...item,
        companyNames: item.companyNames?.join(','),
      };
    });
    let reqObj = {
      mexpertInfoList: mapList,
    };
    extractExpertsRun(reqObj);
  };

  /** 监听抽选专家数据  有则用【抽选专家】 默认返回dataGrid数据*/
  const allExtractData = useMemo(() => {
    if (extractFormRef?.current?.firstForm?.getFieldValue('extractTable')?.length > 0) {
      if (extractExpertsData?.length > 0) {
        return extractExpertsData;
      }
    }
    return expertDataSource;
  }, [extractFormRef, extractExpertsData, expertDataSource]);

  /** 统计抽选专家个数 */
  const badgeData = useMemo(() => {
    let newData = extractFormRef?.current?.firstForm?.getFieldValue('extractTable');
    let extractCount = 0;
    if (newData?.length > 0) {
      newData?.map((item: any) => {
        extractCount += Number(item.count);
      });
      return extractCount;
    }
  }, [extractFormRef?.current?.firstForm?.getFieldValue('extractTable')]);

  return (
    <>
      <OneModal
        open={true}
        onCancel={onClose}
        centered={true}
        className={className}
        title={!isShowFrom ? '添加专家' : '选择专家'}
        bodyStyle={{ height: '600px', padding: '5px 0px', overflow: 'hidden' }}
        width={document.body.clientWidth * 0.6}
        ref={oneModalRef}
        footer={footerRender()}
        confirmLoading={expertLoading || extractExpertsLoading}
      >
        <Spin spinning={expertLoading || extractExpertsLoading}>
          {isShowFrom && (
            <div className="source-selectExpertModal">
              <Form form={searchForm}>
                <Row gutter={[8, 0]} style={{ padding: '10px 1rem' }}>
                  <Col span={4}>
                    <Form.Item name="fullName">
                      <Input placeholder="姓名" allowClear />
                    </Form.Item>
                  </Col>
                  {/* <Col span={4}>
                  <Form.Item name="phoneMobile">
                    <Input placeholder="联系方式" allowClear />
                  </Form.Item>
                </Col>
                <Col span={4}>
                  <Form.Item name="positionName">
                    <Input placeholder="职务" allowClear />
                  </Form.Item>
                </Col>
                <Col span={4}>
                  <Form.Item name="titleTech">
                    <Input placeholder="职称" allowClear />
                  </Form.Item>
                </Col> */}
                  <Col span={4}>
                    <Form.Item name="companyName">
                      <Input placeholder="工作单位" allowClear />
                    </Form.Item>
                  </Col>
                  <Col span={4}>
                    <Form.Item name="cardNum">
                      <Input placeholder="身份证" allowClear />
                    </Form.Item>
                  </Col>
                  <Col span={12} style={{ textAlign: 'right' }}>
                    <Space>
                      {extractFormRef?.current?.firstForm?.getFieldValue('extractTable') &&
                      extractFormRef?.current?.firstForm?.getFieldValue('extractTable')?.length > 0 ? (
                        <Button type="primary" icon={<SearchOutlined />} onClick={onSearchExtract}>
                          查询
                        </Button>
                      ) : (
                        <Button type="primary" icon={<SearchOutlined />} onClick={onSearch}>
                          查询
                        </Button>
                      )}

                      <Button icon={<RedoOutlined />} onClick={onReset}>
                        重置
                      </Button>
                      <Badge count={badgeData}>
                        <Button icon={<FilterOutlined />} onClick={onExtract}>
                          更多
                        </Button>
                      </Badge>
                    </Space>
                  </Col>
                </Row>
              </Form>
              <div className={'list-table'} style={{ position: 'relative', flex: 'auto', overflow: 'hidden' }}>
                <Table
                  bordered
                  size="small"
                  columns={getSelectExpertsColumns()}
                  // dataSource={expertDataSource}
                  dataSource={allExtractData}
                  loading={false}
                  scroll={{ x: 'true', y: 'true' }}
                  rowKey={(record: any) => record?.expertID ?? record?.id}
                  rowSelection={{
                    type: 'checkbox',
                    onChange: onSelectChange,
                  }}
                  // pagination={expertTableProps as any} //expertTableProps
                  pagination={
                    {
                      ...expertTableProps,
                      showQuickJumper: true,
                      showSizeChanger: true,
                      pageSizeOptions: commonPageSizeOptions,
                    } as any
                  }
                ></Table>

                <ExtractListDrawer
                  visible={isShowExtractModal}
                  expertDataSource={expertDataSource}
                  onClose={() => {
                    setIsShowExtractModal(false);
                  }}
                  ref={extractFormRef}
                />
              </div>
            </div>
          )}
          {!isShowFrom && (
            <div style={{ margin: '10px 1rem' }}>
              <Descriptions config={config} />
            </div>
          )}
        </Spin>
      </OneModal>
    </>
  );
};

export default ExpertsListModal;
